@hintergrund/worker 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/api/cms/handlers/admin-users.handler.d.ts +1 -0
  2. package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
  3. package/dist/api/cms/handlers/admin-users.handler.js +60 -74
  4. package/dist/api/cms/handlers/agent-conversations.handler.d.ts +0 -1
  5. package/dist/api/cms/handlers/agent-conversations.handler.d.ts.map +1 -1
  6. package/dist/api/cms/handlers/agent-conversations.handler.js +0 -7
  7. package/dist/api/cms/handlers/agent-provider.handler.d.ts +12 -0
  8. package/dist/api/cms/handlers/agent-provider.handler.d.ts.map +1 -0
  9. package/dist/api/cms/handlers/agent-provider.handler.js +64 -0
  10. package/dist/api/cms/handlers/auth.handler.d.ts +1 -1
  11. package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
  12. package/dist/api/cms/handlers/auth.handler.js +13 -62
  13. package/dist/api/cms/handlers/dashboard.handler.d.ts +1 -1
  14. package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -1
  15. package/dist/api/cms/handlers/dashboard.handler.js +3 -4
  16. package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
  17. package/dist/api/cms/handlers/github-secrets.handler.js +12 -1
  18. package/dist/api/cms/handlers/integrations.handler.d.ts +5 -0
  19. package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -0
  20. package/dist/api/cms/handlers/integrations.handler.js +24 -0
  21. package/dist/api/cms/handlers/recovery.handler.d.ts +5 -0
  22. package/dist/api/cms/handlers/recovery.handler.d.ts.map +1 -0
  23. package/dist/api/cms/handlers/recovery.handler.js +53 -0
  24. package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
  25. package/dist/api/cms/handlers/setup.handler.js +159 -29
  26. package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -0
  27. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
  28. package/dist/api/cms/handlers/website-repo.handler.js +124 -16
  29. package/dist/api/cms/handlers/website-templates.handler.d.ts +2 -0
  30. package/dist/api/cms/handlers/website-templates.handler.d.ts.map +1 -1
  31. package/dist/api/cms/handlers/website-templates.handler.js +22 -2
  32. package/dist/api/cms/routes/auth.routes.d.ts +1 -1
  33. package/dist/api/cms/routes/auth.routes.d.ts.map +1 -1
  34. package/dist/api/cms/routes/auth.routes.js +7 -2
  35. package/dist/api/cms/routes/index.d.ts +1 -1
  36. package/dist/api/cms/routes/index.d.ts.map +1 -1
  37. package/dist/api/cms/routes/index.js +14 -9
  38. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  39. package/dist/api/emails/handlers/campaigns.handler.js +3 -4
  40. package/dist/api/emails/handlers/invoice.handler.d.ts +8 -15
  41. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
  42. package/dist/api/emails/handlers/invoice.handler.js +142 -170
  43. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  44. package/dist/api/emails/handlers/public.handler.js +27 -8
  45. package/dist/api/emails/handlers/send.handler.d.ts +1 -3
  46. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
  47. package/dist/api/emails/handlers/send.handler.js +18 -65
  48. package/dist/api/emails/handlers/settings.handler.d.ts +60 -12
  49. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
  50. package/dist/api/emails/handlers/settings.handler.js +38 -94
  51. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  52. package/dist/api/emails/routes/admin.routes.js +5 -6
  53. package/dist/api/emails/routes/mail-events.routes.d.ts +5 -0
  54. package/dist/api/emails/routes/mail-events.routes.d.ts.map +1 -0
  55. package/dist/api/emails/routes/mail-events.routes.js +29 -0
  56. package/dist/api/emails/routes/mail.routes.d.ts +5 -0
  57. package/dist/api/emails/routes/mail.routes.d.ts.map +1 -0
  58. package/dist/api/emails/routes/mail.routes.js +188 -0
  59. package/dist/api/shop/handlers/products.handler.d.ts +2 -2
  60. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  61. package/dist/api/shop/handlers/products.handler.js +30 -8
  62. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  63. package/dist/api/shop/handlers/public.handler.js +17 -66
  64. package/dist/index.d.ts +11 -1
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +30 -22
  67. package/dist/lib/brand.d.ts +6 -0
  68. package/dist/lib/brand.d.ts.map +1 -0
  69. package/dist/lib/brand.js +29 -0
  70. package/dist/lib/config.d.ts +5 -11
  71. package/dist/lib/config.d.ts.map +1 -1
  72. package/dist/lib/config.js +21 -39
  73. package/dist/lib/email-template.d.ts +2 -5
  74. package/dist/lib/email-template.d.ts.map +1 -1
  75. package/dist/lib/email-template.js +6 -27
  76. package/dist/lib/email.d.ts +20 -11
  77. package/dist/lib/email.d.ts.map +1 -1
  78. package/dist/lib/email.js +29 -19
  79. package/dist/lib/github.d.ts +1 -1
  80. package/dist/lib/github.d.ts.map +1 -1
  81. package/dist/lib/github.js +13 -4
  82. package/dist/lib/integration-health.d.ts +18 -0
  83. package/dist/lib/integration-health.d.ts.map +1 -0
  84. package/dist/lib/integration-health.js +51 -0
  85. package/dist/lib/invoice.d.ts +13 -0
  86. package/dist/lib/invoice.d.ts.map +1 -0
  87. package/dist/lib/invoice.js +41 -0
  88. package/dist/lib/launch-draft.d.ts +14 -0
  89. package/dist/lib/launch-draft.d.ts.map +1 -0
  90. package/dist/lib/launch-draft.js +45 -0
  91. package/dist/lib/launch.d.ts +3 -0
  92. package/dist/lib/launch.d.ts.map +1 -0
  93. package/dist/lib/launch.js +18 -0
  94. package/dist/lib/mail-schema.d.ts +5 -0
  95. package/dist/lib/mail-schema.d.ts.map +1 -0
  96. package/dist/lib/mail-schema.js +62 -0
  97. package/dist/lib/mail.d.ts +83 -0
  98. package/dist/lib/mail.d.ts.map +1 -0
  99. package/dist/lib/mail.js +211 -0
  100. package/dist/lib/project-db.d.ts +5 -4
  101. package/dist/lib/project-db.d.ts.map +1 -1
  102. package/dist/lib/project-db.js +27 -42
  103. package/dist/lib/template-installer.d.ts +9 -0
  104. package/dist/lib/template-installer.d.ts.map +1 -0
  105. package/dist/lib/template-installer.js +97 -0
  106. package/dist/lib/template.d.ts.map +1 -1
  107. package/dist/lib/template.js +28 -0
  108. package/dist/lib/user-recovery.d.ts +9 -0
  109. package/dist/lib/user-recovery.d.ts.map +1 -0
  110. package/dist/lib/user-recovery.js +42 -0
  111. package/dist/lib/website-i18n.d.ts +10 -0
  112. package/dist/lib/website-i18n.d.ts.map +1 -0
  113. package/dist/lib/website-i18n.js +195 -0
  114. package/dist/middleware/auth.d.ts +3 -1
  115. package/dist/middleware/auth.d.ts.map +1 -1
  116. package/dist/middleware/auth.js +8 -4
  117. package/package.json +5 -3
  118. package/dist/hintergrund-assets.d.ts +0 -5
  119. package/dist/hintergrund-assets.d.ts.map +0 -1
  120. package/dist/hintergrund-assets.js +0 -11
@@ -2,6 +2,7 @@ import type { Context } from 'hono';
2
2
  import type { HonoEnv } from '../../../index';
3
3
  export declare function listAdminUsers(c: Context<HonoEnv>): Promise<Response>;
4
4
  export declare function createAdminUser(c: Context<HonoEnv>): Promise<Response>;
5
+ export declare function sendUserRecovery(c: Context<HonoEnv>): Promise<Response>;
5
6
  export declare function patchAdminUser(c: Context<HonoEnv>): Promise<Response>;
6
7
  export declare function deleteAdminUser(c: Context<HonoEnv>): Promise<Response>;
7
8
  //# sourceMappingURL=admin-users.handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"admin-users.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/admin-users.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAwB9C,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAU3E;AAED,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAE5E;AA8BD,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgC3E;AAED,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiB5E"}
1
+ {"version":3,"file":"admin-users.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/admin-users.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAS9C,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI3E;AACD,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmB5E;AACD,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAM7E;AACD,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgB3E;AACD,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAS5E"}
@@ -1,96 +1,82 @@
1
- import { hashPw } from '../../../lib/auth/crypto';
2
1
  import { createId, ensureSchema, nowSeconds } from '../../../lib/project-db';
3
- const LOGIN_METHODS = ['password', 'otp'];
4
- function userToResponse(user) {
5
- return {
6
- id: user.id,
7
- email: user.email,
8
- name: user.name,
9
- loginMethod: user.login_method,
10
- disabledAt: user.disabled_at,
11
- createdAt: user.created_at,
12
- updatedAt: user.updated_at,
13
- hasPassword: !!user.password_hash,
14
- };
2
+ import { sendRecovery, validEmail } from '../../../lib/user-recovery';
3
+ function userToResponse(user, currentId) {
4
+ return { id: user.id, email: user.email, name: user.name, disabledAt: user.disabled_at,
5
+ createdAt: user.created_at, updatedAt: user.updated_at, hasPassword: !!user.password_hash,
6
+ isFirst: user.initial_admin === 1, isCurrent: user.id === currentId };
15
7
  }
16
8
  export async function listAdminUsers(c) {
17
9
  const db = await ensureSchema(c.env);
18
- const { results } = await db
19
- .prepare('SELECT * FROM admin_users ORDER BY created_at ASC, id ASC')
20
- .all();
21
- const users = (results ?? []).map((user, index) => ({
22
- ...userToResponse(user),
23
- isFirst: index === 0,
24
- }));
25
- return c.json({ users });
10
+ const { results } = await db.prepare('SELECT * FROM admin_users ORDER BY created_at ASC, id ASC').all();
11
+ return c.json({ users: results.map(user => userToResponse(user, c.get('user')?.userId)) });
26
12
  }
27
13
  export async function createAdminUser(c) {
28
- return createAdminUserFromBody(c, await c.req.json(), 201);
29
- }
30
- async function createAdminUserFromBody(c, body, status) {
31
- const email = String(body.email ?? '').toLowerCase().trim();
32
- const name = body.name ? String(body.name).trim() : null;
33
- const loginMethod = LOGIN_METHODS.includes(body.loginMethod) ? body.loginMethod : 'otp';
34
- if (!email) {
35
- return c.json({ error: 'Email is required' }, 400);
36
- }
37
- if (loginMethod === 'password' && !body.passwordHash && !body.password) {
38
- return c.json({ error: 'password is required for password users' }, 400);
39
- }
14
+ const body = await c.req.json();
15
+ const email = typeof body.email === 'string' ? body.email.toLowerCase().trim() : '';
16
+ const name = typeof body.name === 'string' ? body.name.trim().slice(0, 200) : null;
17
+ if (!validEmail(email))
18
+ return c.json({ error: 'A valid primary email address is required.' }, 400);
40
19
  const db = await ensureSchema(c.env);
41
20
  const now = nowSeconds();
42
21
  const id = createId('user');
43
- const passwordHash = body.password ? await hashPw(String(body.password), c.env.SECRET ?? '') : body.passwordHash ?? null;
44
- await db
45
- .prepare(`INSERT INTO admin_users (id, email, name, password_hash, login_method, disabled_at, created_at, updated_at)
46
- VALUES (?, ?, ?, ?, ?, NULL, ?, ?)`)
47
- .bind(id, email, name, passwordHash, loginMethod, now, now)
48
- .run();
49
- const user = await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(id).first();
50
- return c.json({ user: userToResponse(user) }, status);
22
+ const result = await db.prepare(`INSERT INTO admin_users (id, email, name, password_hash, login_method, created_at, updated_at)
23
+ VALUES (?, ?, ?, NULL, 'password', ?, ?) ON CONFLICT(email) DO NOTHING`).bind(id, email, name, now, now).run();
24
+ if (!result.meta.changes)
25
+ return c.json({ error: 'A user with this email already exists.' }, 409);
26
+ const user = (await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(id).first());
27
+ try {
28
+ await sendRecovery(c.env, user, new URL(c.req.url).origin);
29
+ return c.json({ user: userToResponse(user), message: 'User created. Password setup email sent.' }, 201);
30
+ }
31
+ catch (error) {
32
+ // Keep a visible pending account so the administrator can resend, not create duplicates.
33
+ return c.json({ user: userToResponse(user), message: 'User created, but the invitation could not be sent. Fix email settings and resend the invitation.', invitationSent: false }, 201);
34
+ }
35
+ }
36
+ export async function sendUserRecovery(c) {
37
+ const db = await ensureSchema(c.env);
38
+ const user = await db.prepare('SELECT * FROM admin_users WHERE id = ? AND disabled_at IS NULL').bind(c.req.param('id')).first();
39
+ if (!user)
40
+ return c.json({ error: 'Active user not found.' }, 404);
41
+ try {
42
+ await sendRecovery(c.env, user, new URL(c.req.url).origin);
43
+ return c.json({ success: true, message: 'Password setup email sent to the primary email address.' });
44
+ }
45
+ catch (error) {
46
+ return c.json({ error: error instanceof Error ? error.message : 'Unable to send email.' }, 400);
47
+ }
51
48
  }
52
49
  export async function patchAdminUser(c) {
53
50
  const userId = c.req.param('id');
54
- if (!userId)
55
- return c.json({ error: 'Missing user id' }, 400);
56
51
  const body = await c.req.json();
52
+ if (body.email !== undefined || body.password !== undefined || body.passwordHash !== undefined)
53
+ return c.json({ error: 'Credentials can only be set through a link sent to the primary email. Create a new user to change the primary address.' }, 400);
54
+ if (body.disabled !== undefined && typeof body.disabled !== 'boolean')
55
+ return c.json({ error: 'Invalid disabled state.' }, 400);
57
56
  const db = await ensureSchema(c.env);
58
57
  const existing = await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(userId).first();
59
- if (!existing) {
60
- return c.json({ error: 'User not found' }, 404);
61
- }
62
- const email = body.email === undefined ? existing.email : String(body.email).toLowerCase().trim();
63
- const name = body.name === undefined ? existing.name : (body.name ? String(body.name).trim() : null);
64
- const loginMethod = body.loginMethod === undefined || !LOGIN_METHODS.includes(body.loginMethod)
65
- ? existing.login_method
66
- : body.loginMethod;
67
- const disabledAt = body.disabled === undefined ? existing.disabled_at : (body.disabled ? nowSeconds() : null);
68
- const passwordHash = body.password
69
- ? await hashPw(String(body.password), c.env.SECRET ?? '')
70
- : (body.passwordHash === undefined ? existing.password_hash : body.passwordHash);
71
- const now = nowSeconds();
72
- await db
73
- .prepare(`UPDATE admin_users
74
- SET email = ?, name = ?, password_hash = ?, login_method = ?, disabled_at = ?, updated_at = ?
75
- WHERE id = ?`)
76
- .bind(email, name, passwordHash, loginMethod, disabledAt, now, userId)
77
- .run();
78
- const user = await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(userId).first();
79
- return c.json({ user: userToResponse(user) });
58
+ if (!existing)
59
+ return c.json({ error: 'User not found.' }, 404);
60
+ if (body.disabled && (existing.initial_admin === 1 || userId === c.get('user')?.userId))
61
+ return c.json({ error: 'You cannot disable yourself or the original owner.' }, 400);
62
+ const name = typeof body.name === 'string' ? body.name.trim().slice(0, 200) : existing.name;
63
+ const disabled = body.disabled === undefined ? existing.disabled_at : body.disabled ? nowSeconds() : null;
64
+ await db.batch([
65
+ db.prepare('UPDATE admin_users SET name = ?, disabled_at = ?, updated_at = ? WHERE id = ?').bind(name, disabled, Math.max(nowSeconds(), existing.updated_at + 1), userId),
66
+ db.prepare('DELETE FROM user_recovery WHERE user_id = ?').bind(userId),
67
+ ]);
68
+ return c.json({ success: true });
80
69
  }
81
70
  export async function deleteAdminUser(c) {
82
- const currentUser = c.get('user');
83
71
  const userId = c.req.param('id');
84
- if (currentUser?.userId === userId) {
85
- return c.json({ error: 'You cannot delete your own admin user' }, 400);
86
- }
72
+ if (c.get('user')?.userId === userId)
73
+ return c.json({ error: 'You cannot delete yourself.' }, 400);
87
74
  const db = await ensureSchema(c.env);
88
- const firstUser = await db
89
- .prepare('SELECT id FROM admin_users ORDER BY created_at ASC, id ASC LIMIT 1')
90
- .first();
91
- if (firstUser?.id === userId) {
92
- return c.json({ error: 'The original admin user cannot be deleted' }, 400);
93
- }
75
+ const existing = await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(userId).first();
76
+ if (!existing)
77
+ return c.json({ error: 'User not found.' }, 404);
78
+ if (existing.initial_admin === 1)
79
+ return c.json({ error: 'The original owner cannot be deleted.' }, 400);
94
80
  await db.prepare('DELETE FROM admin_users WHERE id = ?').bind(userId).run();
95
81
  return c.json({ success: true });
96
82
  }
@@ -3,5 +3,4 @@ import type { HonoEnv } from '../../../index';
3
3
  export declare function listConversations(c: Context<HonoEnv>): Promise<Response>;
4
4
  export declare function upsertConversation(c: Context<HonoEnv>): Promise<Response>;
5
5
  export declare function deleteConversation(c: Context<HonoEnv>): Promise<Response>;
6
- export declare function getAgentApiKey(c: Context<HonoEnv>): Promise<Response>;
7
6
  //# sourceMappingURL=agent-conversations.handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-conversations.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/agent-conversations.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA4B9C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAY9E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8C/E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW/E;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAO3E"}
1
+ {"version":3,"file":"agent-conversations.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/agent-conversations.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA4B9C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAY9E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8C/E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW/E"}
@@ -85,10 +85,3 @@ export async function deleteConversation(c) {
85
85
  .run();
86
86
  return c.json({ success: true });
87
87
  }
88
- export async function getAgentApiKey(c) {
89
- const apiKey = c.env.GEMINI_API_KEY?.trim();
90
- if (!apiKey) {
91
- return c.json({ error: 'Builder agent is not configured' }, 500);
92
- }
93
- return c.json({ apiKey });
94
- }
@@ -0,0 +1,12 @@
1
+ import type { Context } from 'hono';
2
+ import { type AgentProviderName } from '@hintergrund/runtime-contracts';
3
+ import type { Bindings, HonoEnv } from '../../../index';
4
+ /** The provider to use, in declaration order, for projects that configure several. */
5
+ export declare function activeAgentProvider(env: Bindings): AgentProviderName | null;
6
+ export declare function getAgentConfig(c: Context<HonoEnv>): Promise<Response>;
7
+ /**
8
+ * Streams an agent request through to the configured provider. The browser speaks
9
+ * the provider's own protocol, so the body is forwarded verbatim both ways.
10
+ */
11
+ export declare function proxyAgentRequest(c: Context<HonoEnv>): Promise<Response>;
12
+ //# sourceMappingURL=agent-provider.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-provider.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/agent-provider.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAA2C,KAAK,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACjH,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA4BxD,sFAAsF;AACtF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,QAAQ,GAAG,iBAAiB,GAAG,IAAI,CAE3E;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAE3E;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8B9E"}
@@ -0,0 +1,64 @@
1
+ import { AGENT_PROVIDERS, AGENT_PROVIDER_SECRETS } from '@hintergrund/runtime-contracts';
2
+ /**
3
+ * Where each provider's requests go, and how its key is presented. Provider keys
4
+ * are Worker secrets and never reach the browser: the admin agents run in the
5
+ * client and call `/api/admin/agent/llm/*`, which attaches the key here.
6
+ */
7
+ const PROVIDER_ENDPOINTS = {
8
+ google: {
9
+ baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
10
+ authorize: (headers, key) => headers.set('x-goog-api-key', key),
11
+ },
12
+ deepseek: {
13
+ baseUrl: 'https://api.deepseek.com',
14
+ authorize: (headers, key) => headers.set('authorization', `Bearer ${key}`),
15
+ },
16
+ };
17
+ function providerKey(env, provider) {
18
+ const value = env[AGENT_PROVIDER_SECRETS[provider]];
19
+ if (typeof value !== 'string')
20
+ return undefined;
21
+ const key = value.trim();
22
+ return key && key !== 'NOT_CONFIGURED' ? key : undefined;
23
+ }
24
+ /** The provider to use, in declaration order, for projects that configure several. */
25
+ export function activeAgentProvider(env) {
26
+ return AGENT_PROVIDERS.find((provider) => providerKey(env, provider)) ?? null;
27
+ }
28
+ export async function getAgentConfig(c) {
29
+ return c.json({ provider: activeAgentProvider(c.env) });
30
+ }
31
+ /**
32
+ * Streams an agent request through to the configured provider. The browser speaks
33
+ * the provider's own protocol, so the body is forwarded verbatim both ways.
34
+ */
35
+ export async function proxyAgentRequest(c) {
36
+ const provider = activeAgentProvider(c.env);
37
+ if (!provider)
38
+ return c.json({ error: 'No AI provider is configured for this project.' }, 503);
39
+ const { baseUrl, authorize } = PROVIDER_ENDPOINTS[provider];
40
+ const headers = new Headers();
41
+ for (const name of ['content-type', 'accept']) {
42
+ const value = c.req.header(name);
43
+ if (value)
44
+ headers.set(name, value);
45
+ }
46
+ authorize(headers, providerKey(c.env, provider));
47
+ const { search } = new URL(c.req.url);
48
+ const upstream = await fetch(`${baseUrl}/${c.req.param('path')}${search}`, {
49
+ method: c.req.method,
50
+ headers,
51
+ body: c.req.raw.body,
52
+ // The Workers runtime requires this when forwarding a streaming request body.
53
+ duplex: 'half',
54
+ signal: c.req.raw.signal,
55
+ });
56
+ // Pass the upstream body straight through so tokens reach the UI as they arrive.
57
+ return new Response(upstream.body, {
58
+ status: upstream.status,
59
+ headers: {
60
+ 'content-type': upstream.headers.get('content-type') ?? 'application/json',
61
+ 'cache-control': 'no-store',
62
+ },
63
+ });
64
+ }
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'hono';
2
- import { HonoEnv } from '../../../index';
2
+ import type { HonoEnv } from '../../../index';
3
3
  export declare function login(c: Context<HonoEnv>): Promise<Response>;
4
4
  export declare function logout(c: Context<HonoEnv>): Promise<Response>;
5
5
  //# sourceMappingURL=auth.handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/auth.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAgBzC,wBAAsB,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmBlE;AAiFD,wBAAsB,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAOnE"}
1
+ {"version":3,"file":"auth.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/auth.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAY9C,wBAAsB,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoBlE;AAeD,wBAAsB,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAOnE"}
@@ -1,25 +1,26 @@
1
1
  import { readRequestBody, verifyPw } from '../../../lib/auth/crypto';
2
2
  import { signWithPayload } from '../../../lib/auth/jwt';
3
3
  import { loadConfig } from '../../../lib/config';
4
- import { sendEmailOtp } from '../../../lib/email';
5
- import { createId, ensureSchema, getAdminUserByEmail, issueSessionForUser, nowSeconds, sha256Base64Url } from '../../../lib/project-db';
4
+ import { rateLimit } from '../../../lib/user-recovery';
5
+ import { getAdminUserByEmail, issueSessionForUser } from '../../../lib/project-db';
6
6
  export async function login(c) {
7
7
  try {
8
+ if (!await rateLimit(c.env, `login:${c.req.header('CF-Connecting-IP') || 'local'}`, 30, 900))
9
+ return loginError('Too many attempts. Try again later.', 429);
8
10
  const appConfig = loadConfig(c.env);
9
- const body = await readRequestBody(c.req.raw);
11
+ const body = (await readRequestBody(c.req.raw));
10
12
  const isSecure = c.req.url.startsWith('https://');
11
13
  const email = body.email?.toLowerCase().trim();
12
- if (!email)
13
- return loginError('Email is required', 400);
14
+ const password = body.password;
15
+ if (!email || !password)
16
+ return loginError('Email and password are required', 400);
14
17
  const user = await getAdminUserByEmail(c.env, email);
15
- if (!user)
18
+ if (!user || !user.password_hash)
19
+ return loginError('Invalid credentials', 401);
20
+ if (!(await verifyPw(user.password_hash, password, appConfig.global.hgSecret))) {
16
21
  return loginError('Invalid credentials', 401);
17
- if (body.password)
18
- return await handleProjectPasswordLogin(c, body.password, appConfig.global.hgSecret, user, isSecure);
19
- if (user.login_method === 'password') {
20
- return c.json({ success: true, requirePassword: true });
21
22
  }
22
- return await handleProjectEmailOtpLogin(c, body.otp, user, appConfig, isSecure);
23
+ return signedInResponse(appConfig.global.hgSecret, user, isSecure);
23
24
  }
24
25
  catch (error) {
25
26
  console.error('Login error:', error);
@@ -29,58 +30,8 @@ export async function login(c) {
29
30
  function loginError(message, status) {
30
31
  return new Response(JSON.stringify({ success: false, message }), { status });
31
32
  }
32
- async function handleProjectPasswordLogin(c, password, hgSecret, user, isSecure) {
33
- if (user.login_method !== 'password' || !user.password_hash)
34
- return loginError('Password sign-in is not enabled for this user', 400);
35
- if (!(await verifyPw(user.password_hash, password, hgSecret)))
36
- return loginError('Invalid credentials', 401);
37
- return signedInResponse(hgSecret, user, isSecure);
38
- }
39
- async function handleProjectEmailOtpLogin(c, otp, user, appConfig, isSecure) {
40
- if (user.login_method !== 'otp')
41
- return loginError('Email-code sign-in is not enabled for this user', 400);
42
- const emailsConfig = appConfig.emails;
43
- if (!emailsConfig?.emailApiKey)
44
- return loginError('Emails module is not configured', 500);
45
- const db = await ensureSchema(c.env);
46
- const now = nowSeconds();
47
- const submittedOtp = otp?.trim();
48
- if (submittedOtp) {
49
- if (!/^\d{6}$/.test(submittedOtp))
50
- return loginError('Enter the six-digit code from your email.', 400);
51
- const codeHash = await otpHash(user.id, submittedOtp, appConfig.global.hgSecret);
52
- const result = await db.prepare(`UPDATE admin_email_otps
53
- SET used_at = ?
54
- WHERE user_id = ? AND code_hash = ? AND used_at IS NULL AND expires_at > ?`).bind(now, user.id, codeHash, now).run();
55
- if (!result.meta.changes)
56
- return loginError('That code is invalid or has expired. Request a new one.', 401);
57
- return signedInResponse(appConfig.global.hgSecret, user, isSecure);
58
- }
59
- const code = emailOtp();
60
- const codeHash = await otpHash(user.id, code, appConfig.global.hgSecret);
61
- await db.batch([
62
- db.prepare('DELETE FROM admin_email_otps WHERE user_id = ?').bind(user.id),
63
- db.prepare(`INSERT INTO admin_email_otps (id, user_id, code_hash, expires_at, used_at, created_at)
64
- VALUES (?, ?, ?, ?, NULL, ?)`).bind(createId('otp'), user.id, codeHash, now + 15 * 60, now),
65
- ]);
66
- const { settings } = await import('../../emails/handlers/settings.handler').then(({ readEmailSettings }) => readEmailSettings(c.env));
67
- await sendEmailOtp({
68
- to: user.email,
69
- apiKey: emailsConfig.emailApiKey,
70
- fromEmail: settings.fromEmail ?? '',
71
- fromName: settings.fromName,
72
- code,
73
- });
74
- return c.json({ success: true, otpRequired: true, message: 'Check your email for a six-digit sign-in code.' });
75
- }
76
- function emailOtp() {
77
- return crypto.getRandomValues(new Uint32Array(1))[0].toString().slice(-6).padStart(6, '0');
78
- }
79
- async function otpHash(userId, code, secret) {
80
- return sha256Base64Url(`${userId}.${code}.${secret}`);
81
- }
82
33
  async function signedInResponse(secret, user, isSecure) {
83
- const token = await signWithPayload(secret, issueSessionForUser(user));
34
+ const token = await signWithPayload(secret, await issueSessionForUser(user));
84
35
  const secureCookie = isSecure ? '; Secure' : '';
85
36
  return new Response(JSON.stringify({ success: true }), {
86
37
  status: 200,
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'hono';
2
- import { Bindings } from '../../..';
2
+ import type { Bindings } from '../../..';
3
3
  export declare function getDashboard(c: Context<{
4
4
  Bindings: Bindings;
5
5
  }>): Promise<Response>;
@@ -1 +1 @@
1
- {"version":3,"file":"dashboard.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/dashboard.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGpC,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAYxF"}
1
+ {"version":3,"file":"dashboard.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/dashboard.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGzC,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAWxF"}
@@ -1,15 +1,14 @@
1
1
  import { getTemplate } from '../../../lib/template';
2
- import { loadConfig, getAdminConfig } from '../../../lib/config';
2
+ import { getAdminConfig } from '../../../lib/config';
3
3
  export async function getDashboard(c) {
4
4
  try {
5
- const appConfig = loadConfig(c.env);
6
- const adminConfig = getAdminConfig(appConfig);
5
+ const adminConfig = getAdminConfig();
7
6
  const configParams = `config='${JSON.stringify(adminConfig)}'`;
8
7
  return c.html(getTemplate('admin', c.env.UI_BASE_URL, configParams));
9
8
  }
10
9
  catch (error) {
11
10
  // Fallback to default config if parsing fails
12
- const configParams = 'config=\'{"loginMethod":"password"}\'';
11
+ const configParams = 'config=\'{}\'';
13
12
  return c.html(getTemplate('admin', c.env.UI_BASE_URL, configParams));
14
13
  }
15
14
  }
@@ -1 +1 @@
1
- {"version":3,"file":"github-secrets.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/github-secrets.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EAAsB,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAwC9C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkB/E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAe/E;AAED,YAAY,EAAE,YAAY,EAAE,CAAC"}
1
+ {"version":3,"file":"github-secrets.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/github-secrets.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EAAsB,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA6C9C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuB/E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAe/E;AAED,YAAY,EAAE,YAAY,EAAE,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { getGitHubConfig } from '../../../lib/config';
2
2
  import { createGitHubClient } from '../../../lib/github';
3
+ import { checkIntegrationKey, INTEGRATION_SECRETS } from '../../../lib/integration-health';
3
4
  const SECRET_NAME = /^[A-Z_][A-Z0-9_]*$/;
4
5
  const MAX_SECRET_BYTES = 64 * 1024;
5
6
  // These are the only Actions secrets consumed by the generated deployment
@@ -12,11 +13,15 @@ const DEPLOYABLE_ACTION_SECRET_NAMES = new Set([
12
13
  'STRIPE_WEBHOOK_SECRET',
13
14
  'API_KEY',
14
15
  'SETUP_TOKEN',
16
+ 'GEMINI_API_KEY',
17
+ 'DEEPSEEK_API_KEY',
15
18
  ]);
16
19
  const DELETABLE_ACTION_SECRET_NAMES = new Set([
17
20
  'STRIPE_SECRET_KEY',
18
21
  'STRIPE_WEBHOOK_SECRET',
19
22
  'API_KEY',
23
+ 'GEMINI_API_KEY',
24
+ 'DEEPSEEK_API_KEY',
20
25
  ]);
21
26
  function secretName(value) {
22
27
  const name = value.trim();
@@ -53,8 +58,14 @@ export async function upsertGitHubSecret(c) {
53
58
  if (new TextEncoder().encode(body.value).byteLength > MAX_SECRET_BYTES) {
54
59
  return c.json({ error: 'Secret value exceeds GitHub’s 64 KB limit.' }, 400);
55
60
  }
61
+ const provider = Object.keys(INTEGRATION_SECRETS).find(provider => INTEGRATION_SECRETS[provider] === name);
62
+ if (provider) {
63
+ const health = await checkIntegrationKey(provider, body.value);
64
+ if (!health.valid)
65
+ return c.json({ error: health.message }, 400);
66
+ }
56
67
  const client = createGitHubClient(getGitHubConfig(c.env));
57
- await client.setActionsSecret(name, body.value);
68
+ await client.setActionsSecret(name, provider ? body.value.trim() : body.value);
58
69
  const deploy = body.deploy !== false;
59
70
  const deploymentStarted = deploy ? await dispatchDeploy(c) : false;
60
71
  return c.json({ success: true, deploymentStarted });
@@ -0,0 +1,5 @@
1
+ import type { Context } from 'hono';
2
+ import type { HonoEnv } from '../../../index';
3
+ export declare const testSetupIntegration: (c: Context<HonoEnv>) => Promise<Response>;
4
+ export declare const testIntegration: (c: Context<HonoEnv>) => Promise<Response>;
5
+ //# sourceMappingURL=integrations.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integrations.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/integrations.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAoB9C,eAAO,MAAM,oBAAoB,GAAI,GAAG,OAAO,CAAC,OAAO,CAAC,sBAAmB,CAAC;AAC5E,eAAO,MAAM,eAAe,GAAI,GAAG,OAAO,CAAC,OAAO,CAAC,sBAAoB,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { checkIntegrationKey, INTEGRATION_SECRETS, isIntegrationProvider } from '../../../lib/integration-health';
2
+ import { hasValidSetupToken, projectNeedsSetup } from './setup.handler';
3
+ async function check(c, setup) {
4
+ c.header('Cache-Control', 'no-store');
5
+ const origin = c.req.header('origin');
6
+ if (origin && origin !== new URL(c.req.url).origin)
7
+ return c.json({ error: 'Invalid origin.' }, 403);
8
+ const body = await c.req.json().catch(() => null);
9
+ if (!body)
10
+ return c.json({ error: 'Invalid request.' }, 400);
11
+ if (setup && (!(await hasValidSetupToken(c.env, body.setupToken)) || !(await projectNeedsSetup(c)))) {
12
+ return c.json({ error: 'Invalid or expired setup link.' }, 403);
13
+ }
14
+ const provider = c.req.param('provider') ?? '';
15
+ if (!isIntegrationProvider(provider))
16
+ return c.json({ error: 'Unsupported integration.' }, 400);
17
+ if (body.key !== undefined && typeof body.key !== 'string')
18
+ return c.json({ error: 'Invalid key.' }, 400);
19
+ const stored = provider === 'plunk' ? c.env.API_KEY || c.env.PLUNK_SECRET_KEY : c.env[INTEGRATION_SECRETS[provider]];
20
+ const key = typeof body.key === 'string' ? body.key : setup ? '' : stored ?? '';
21
+ return c.json(await checkIntegrationKey(provider, key));
22
+ }
23
+ export const testSetupIntegration = (c) => check(c, true);
24
+ export const testIntegration = (c) => check(c, false);
@@ -0,0 +1,5 @@
1
+ import type { Context } from 'hono';
2
+ import type { HonoEnv } from '../../../index';
3
+ export declare function requestPasswordReset(c: Context<HonoEnv>): Promise<Response>;
4
+ export declare function completePasswordReset(c: Context<HonoEnv>): Promise<Response>;
5
+ //# sourceMappingURL=recovery.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recovery.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/recovery.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAK9C,wBAAsB,oBAAoB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAcjF;AAED,wBAAsB,qBAAqB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoBlF"}
@@ -0,0 +1,53 @@
1
+ import { ensureSchema, nowSeconds, sha256Base64Url } from '../../../lib/project-db';
2
+ import { hashPw } from '../../../lib/auth/crypto';
3
+ import { rateLimit, sendRecovery, validEmail, validPassword } from '../../../lib/user-recovery';
4
+ export async function requestPasswordReset(c) {
5
+ const generic = { success: true, message: 'If an active account exists, a password setup link will be sent to its primary email address.' };
6
+ const body = await c.req.json();
7
+ const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
8
+ if (!validEmail(email))
9
+ return c.json(generic);
10
+ const ip = c.req.header('CF-Connecting-IP') || 'local';
11
+ if (!await rateLimit(c.env, `recovery-ip:${ip}`, 10, 3600))
12
+ return c.json(generic);
13
+ // Identical response and asynchronous delivery avoid exposing account existence/provider failures.
14
+ c.executionCtx.waitUntil((async () => {
15
+ const db = await ensureSchema(c.env);
16
+ const user = await db.prepare('SELECT * FROM admin_users WHERE email = ? AND disabled_at IS NULL').bind(email).first();
17
+ if (user) {
18
+ try {
19
+ await sendRecovery(c.env, user, new URL(c.req.url).origin);
20
+ }
21
+ catch {
22
+ console.warn('Account recovery delivery unavailable');
23
+ }
24
+ }
25
+ })());
26
+ return c.json(generic);
27
+ }
28
+ export async function completePasswordReset(c) {
29
+ const body = await c.req.json();
30
+ if (typeof body.token !== 'string' || !/^[a-f0-9]{64}$/.test(body.token))
31
+ return c.json({ error: 'Invalid or expired link.' }, 400);
32
+ if (!validPassword(body.password))
33
+ return c.json({ error: 'Use a password between 12 and 256 characters.' }, 400);
34
+ if (!await rateLimit(c.env, `reset-ip:${c.req.header('CF-Connecting-IP') || 'local'}`, 20, 3600))
35
+ return c.json({ error: 'Too many attempts. Try again later.' }, 429);
36
+ if (!c.env.SECRET)
37
+ return c.json({ error: 'Server configuration error.' }, 503);
38
+ const db = await ensureSchema(c.env);
39
+ const digest = await sha256Base64Url(body.token);
40
+ const now = nowSeconds();
41
+ const passwordHash = await hashPw(body.password, c.env.SECRET);
42
+ // Batch is transactional: token consumption and credential update cannot race or partially commit.
43
+ const results = await db.batch([
44
+ db.prepare(`UPDATE admin_users SET password_hash = ?, updated_at = ? WHERE disabled_at IS NULL AND id IN
45
+ (SELECT user_id FROM user_recovery WHERE token_hash = ? AND expires_at > ?)`)
46
+ .bind(passwordHash, now, digest, now),
47
+ db.prepare('DELETE FROM user_recovery WHERE token_hash = ?').bind(digest),
48
+ ]);
49
+ if (!results[0].meta.changes)
50
+ return c.json({ error: 'Invalid or expired link.' }, 400);
51
+ c.header('Set-Cookie', `token=; HttpOnly; Path=/; SameSite=Strict; Max-Age=0${new URL(c.req.url).protocol === 'https:' ? '; Secure' : ''}`);
52
+ return c.json({ success: true, message: 'Password saved. Sign in with your primary email address.' });
53
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"setup.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/setup.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AASpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAuB9C,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQtG;AAQD,uFAAuF;AACvF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAIzE;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmHzE;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7E"}
1
+ {"version":3,"file":"setup.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/setup.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAYpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAwB9C,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQtG;AAQD,uFAAuF;AACvF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAUzE;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6NzE;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7E"}